/**     
* @Title: CustomUserService.java   
* @Package me.security.example.security   
* @Description: TODO   
* @author xaoyaoyao
* @date 2017年8月23日 下午12:16:24
*/
package me.security.example.security;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import me.security.example.dao.PermissionDao;
import me.security.example.dao.UserDao;
import me.security.example.domain.Permission;
import me.security.example.domain.SysUser;

/**
 * @ClassName: CustomUserService
 * @Description: TODO
 * @author xaoyaoyao
 * @date 2017年8月23日 下午12:16:24
 * 
 */
@Service
public class CustomUserService implements UserDetailsService {

	@Autowired
	UserDao userDao;

	@Autowired
	PermissionDao permissionDao;

	@Override
	public UserDetails loadUserByUsername(String username) {
		SysUser user = userDao.findByUserName(username);
		if (user != null) {
			List<Permission> permissions = permissionDao.findByAdminUserId(user.getId());
			if (!CollectionUtils.isEmpty(permissions)) {
				List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
				for (Permission permission : permissions) {
					if (permission != null && permission.getName() != null) {
						GrantedAuthority grantedAuthority = new MyGrantedAuthority(permission.getUrl(),
								permission.getMethod());
						grantedAuthorities.add(grantedAuthority);
					}
				}
				return new User(user.getUsername(), user.getPassword(), grantedAuthorities);
			}
		}
		throw new UsernameNotFoundException("admin: " + username + " do not exist!");
	}
}
